package edu.isquen.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.isquen.core.admin.model.Superuser;
import edu.isquen.core.user.model.User;

public class SecurityFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8607461135742154076L;

	public void doFilter(ServletRequest req, ServletResponse res,	FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) res;
		request.setCharacterEncoding("UTF-8");
		String url=request.getRequestURI();
		HttpSession session = request.getSession();
		if(isNeedToCheck(url)){
			if(isBackURL(url)){
				Superuser user=(Superuser) session.getAttribute(Superuser.ADMIN_USER);
				if(user!=null && user.getLoginno()!=null && !user.getLoginpwd().equals("")){
					chain.doFilter(request, response);
					return ;
				}else{
					response.sendRedirect(request.getContextPath()+"/common/error.jsp?errorMsg="+Superuser.ADMIN_USER);
				}
			}else if(isFrontURL(url)){
				User user=(User) session.getAttribute(User.front_USER);
				if(user!=null && user.getLoginno()!=null && !user.getLoginpwd().equals("")){
					chain.doFilter(request, response);
					return ;
				}else{
					response.sendRedirect(request.getContextPath()+"/common/error.jsp?errorMsg="+User.front_USER);
				}
			}else{
				chain.doFilter(request, response);
				return ;
			}
		}else{
			chain.doFilter(request, response);
			return ;
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
	
	public Boolean isFrontURL(String url){
		Boolean rtn=false;
		if(url.indexOf("portal")>0){
			rtn=true;
		}
		return rtn;
	}
	
	public Boolean isBackURL(String url){
		Boolean rtn=false;
		if(url.indexOf("core")>0){
			rtn=true;
		}
		return rtn;
	}
	
	public Boolean isNeedToCheck(String url){
		if(url.indexOf(".css")>0 || url.indexOf(".gif")>0 || url.indexOf(".jpg")>0){ //资源文件URL
			return false;
		}else if(url.indexOf(".js")>0){
			if(url.indexOf(".jsp")<0){
				return false;
			}else if(url.indexOf("error.jsp")>0 || url.indexOf("login.jsp")>0){ //特殊页面
				return false;
			}else{
				return true;
			}
		}
		return true;
	}

}
